package com.hyjr.RxTask.netty.client;

import com.hyjr.RxTask.netty.handler.SendCheckResultClientHandler;
import com.hyjr.bean.CheckBean;
import com.hyjr.common.utils.LogUtils;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class SendCheckResultClient {
	
	public void connect(int port, String host, final CheckBean checkBean) throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
					.handler(new ChannelInitializer<Channel>() {
						
						@Override
						protected void initChannel(Channel ch) throws Exception {
							LogUtils.debug("检测端，客户端SendCheckResultClient：发送检测结果Clinet，发送消息内容：" + checkBean.toString());
							ch.pipeline().addLast(new ObjectEncoder());
							ch.pipeline()
									.addLast(new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
							ch.pipeline().addLast(new SendCheckResultClientHandler(checkBean));
						}
					});
			ChannelFuture f = b.connect(host, port).sync();
			f.channel().closeFuture().sync();
			LogUtils.debug("检测端，客户端SendCheckResultClient：关闭" + checkBean.toString());
		} finally {
			group.shutdownGracefully();
		}
	}
}
